/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View.venta;

import Controller.MovimientoC;
import Model.MovimientoM;
import MsSQL.ConMsSQL;
import Util.ArrayListTableModel;
import Util.MiRenderBotonImprimir;
import Util.MiRenderBotonVer;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.InputStream;
import java.sql.Connection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JRSaveContributor;
import net.sf.jasperreports.view.JRViewer;

/**
 *
 * @author Maryluz
 */
public class frmVerMovimientosBloque extends javax.swing.JDialog {

    /**
     * Creates new form frmVerMovimientos
     */
    // TiendaM oMTienda;
    String user;
    String tien;
    JDialog jDialogMostrar;
    private final String PDF = "PDF (*.pdf)";
    private final String DOC = "DOCX (*.docx)";
    private final String XLS = "Single sheet XLS (*.xls)";
    private final List<String> PERMITTED_FILE_TYPES_LIST = Arrays.asList(PDF, DOC, XLS);
    int xIdTienda;
    
    public frmVerMovimientosBloque(java.awt.Frame parent, boolean modal, String usuario, String tienda, int idTienda) {
        super(parent, modal);
        initComponents();
        txtfecha.setFormats("dd/MM/yyyy");
        setLocationRelativeTo(null);
        setResizable(false);
        configurarTabla();
        tblPrenda.setRowHeight(35);
        txtmensaje.setText("");
        xIdTienda=idTienda;
        user = usuario;
        tien = tienda;
        cargarTabla();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblPrenda = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        txtfecha = new org.jdesktop.swingx.JXDatePicker();
        jLabel1 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        txtmensaje = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Movimientos de Prendas en Bloque");

        tblPrenda.setModel(new ArrayListTableModel(
            new Object [][] {},
            new String [] {"  Fecha"," Hora","  Emite","  Recibe","       Tipo"," Cant. Mov.","","",""}
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class,java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false,false,false,false,false,false,false,false,false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblPrenda.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblPrendaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblPrenda);
        tblPrenda.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "ProjSave"); tblPrenda.getActionMap().put("ProjSave", new AbstractAction()         {         public void actionPerformed(ActionEvent e)         {             int fila = tblPrenda.getSelectedRow();              if ((fila > -1))              {                   getMovimiento();              }             }         });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        txtfecha.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        txtfecha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtfechaActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Fecha:");

        jButton2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/PoloS.png"))); // NOI18N
        jButton2.setText("VER  TODOS");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(28, 28, 28)
                .addComponent(txtfecha, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton2)
                        .addComponent(txtfecha, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        txtmensaje.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        txtmensaje.setForeground(new java.awt.Color(0, 0, 204));
        txtmensaje.setText("Mensaje");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtmensaje, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 596, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
                .addGap(10, 10, 10)
                .addComponent(txtmensaje, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tblPrendaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblPrendaMouseClicked
        try {
            MovimientoM oM = new MovimientoM();
            oM = (MovimientoM) tblPrenda.getValueAt(tblPrenda.getSelectedRow(), 8);
            if (evt.getClickCount() == 2 && tblPrenda.getSelectedColumn() == 6) {
                new frmVerMovimientos(null, true, oM.getIdBloque(), user, tien).setVisible(true);
            }
            if (evt.getClickCount() == 2 && tblPrenda.getSelectedColumn() == 7) {
                abrirComprobante(oM.getIdBloque());
            }
        } catch (Exception e) {
        }

    }//GEN-LAST:event_tblPrendaMouseClicked

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        cargarTabla();

    }//GEN-LAST:event_jButton2ActionPerformed

    private void abrirComprobante(String idBloque) {
        try {
            Connection conexion = ConMsSQL.obtenerConexion();
            ClassLoader cl = getClass().getClassLoader();
            InputStream in = cl.getClass().getResourceAsStream("/View/venta/rptMovimiento.jasper");
            HashMap objHashMap = new HashMap();
            objHashMap.put("idBloque", idBloque);
            objHashMap.put("tienda", tien);
            objHashMap.put("representante", user);
//            objHashMap.put("logo", this.getClass().getResourceAsStream("/Image/BOLETA.png"));
//            objHashMap.put("foto", this.getClass().getResourceAsStream("/Image/logo.png"));
            JasperPrint objJasperPrint = JasperFillManager.fillReport(in, objHashMap, conexion);
            //JasperPrintManager.printReport(objJasperPrint, false);
            JRViewer jRViewer = new JRViewer(objJasperPrint);
            List<JRSaveContributor> SaveOptions = Arrays.asList(jRViewer.getSaveContributors());
            Iterator<JRSaveContributor> i = SaveOptions.iterator();

            while (i.hasNext()) {
                JRSaveContributor jsc = i.next();

                if (PERMITTED_FILE_TYPES_LIST.contains(jsc.getDescription())) {
                    continue;
                } else {
                    jRViewer.removeSaveContributor(jsc);
                }
            }

            jDialogMostrar = new JDialog(this, true);
            jDialogMostrar.setTitle("Comprobante del Movimiento");
            jDialogMostrar.setSize(350, 515);
            jDialogMostrar.setLocationRelativeTo(null);
            jDialogMostrar.add(jRViewer);
            jDialogMostrar.setVisible(true);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, "No Existe Información para mostrar");
            //  e.printStackTrace();
            //            jDialogMostrar.setVisible(false);
            // e.printStackTrace();
        }
    }

    private void txtfechaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtfechaActionPerformed
        try {
            DateFormat fechaHora = new SimpleDateFormat("yyyy-MM-dd");
            DateFormat fechaHora2 = new SimpleDateFormat("dd/MM/yyyy");
            String convertido2;
            String convertido = fechaHora.format(txtfecha.getDate());
            MovimientoC oC = new MovimientoC();
            List<MovimientoM> oMs = oC.listarMovimientosBloque(convertido);
            @SuppressWarnings("LocalVariableHidesMemberVariable")
            ArrayList oList;
            limpiarTabla();
            if (oMs != null) {
                int size = oMs.size();
                for (int a = 0; a < size; a++) {
                    oList = new ArrayList();
                    oList.add(oMs.get(a).getFecha());
                    oList.add(oMs.get(a).getHora());
                    oList.add(" " + oMs.get(a).getNomEmite());
                    oList.add(" " + oMs.get(a).getNomRecibe());
                    oList.add(oMs.get(a).getTipoSalida());
                    oList.add(oMs.get(a).getCantidad());
                    oList.add("");
                    oList.add("");
                    oList.add(oMs.get(a));
                    ((ArrayListTableModel) tblPrenda.getModel()).addRow(oList);
                }
            }
            convertido2 = fechaHora2.format(txtfecha.getDate());
            if (tblPrenda.getRowCount() == 0) {
                txtmensaje.setText(" No se encontraron movimientos realizados el " + convertido2 + ".");
                txtmensaje.setForeground(Color.red);
            } else {
                txtmensaje.setText(" Se encontraron " + tblPrenda.getRowCount() + " movimientos realizados el " + convertido2 + ".");
                txtmensaje.setForeground(Color.BLUE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_txtfechaActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblPrenda;
    private org.jdesktop.swingx.JXDatePicker txtfecha;
    private javax.swing.JLabel txtmensaje;
    // End of variables declaration//GEN-END:variables

    private void configurarTabla() {
        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();
        tcr.setHorizontalAlignment(SwingConstants.CENTER);

        tblPrenda.getColumnModel().getColumn(0).setCellRenderer(tcr);
        tblPrenda.getColumnModel().getColumn(1).setCellRenderer(tcr);
        tblPrenda.getColumnModel().getColumn(4).setCellRenderer(tcr);
        tblPrenda.getColumnModel().getColumn(5).setCellRenderer(tcr);
        tblPrenda.getColumnModel().getColumn(6).setCellRenderer(tcr);
        tblPrenda.getColumnModel().getColumn(7).setCellRenderer(tcr);

        tblPrenda.getColumnModel().getColumn(0).setMinWidth(70);
        tblPrenda.getColumnModel().getColumn(0).setPreferredWidth(70);
        tblPrenda.getColumnModel().getColumn(0).setMaxWidth(70);
        tblPrenda.getColumnModel().getColumn(1).setMinWidth(55);
        tblPrenda.getColumnModel().getColumn(1).setPreferredWidth(55);
        tblPrenda.getColumnModel().getColumn(1).setMaxWidth(55);
        tblPrenda.getColumnModel().getColumn(2).setMinWidth(105);
        tblPrenda.getColumnModel().getColumn(2).setPreferredWidth(105);
        tblPrenda.getColumnModel().getColumn(2).setMaxWidth(105);
        tblPrenda.getColumnModel().getColumn(3).setMinWidth(105);
        tblPrenda.getColumnModel().getColumn(3).setPreferredWidth(105);
        tblPrenda.getColumnModel().getColumn(3).setMaxWidth(105);
        tblPrenda.getColumnModel().getColumn(4).setMinWidth(95);
        tblPrenda.getColumnModel().getColumn(4).setPreferredWidth(95);
        tblPrenda.getColumnModel().getColumn(4).setMaxWidth(95);
        tblPrenda.getColumnModel().getColumn(5).setMinWidth(70);
        tblPrenda.getColumnModel().getColumn(5).setPreferredWidth(70);
        tblPrenda.getColumnModel().getColumn(5).setMaxWidth(70);
        tblPrenda.getColumnModel().getColumn(8).setMinWidth(0);
        tblPrenda.getColumnModel().getColumn(8).setPreferredWidth(0);
        tblPrenda.getColumnModel().getColumn(8).setMaxWidth(0);

        tblPrenda.getColumnModel().getColumn(7).setCellRenderer(new MiRenderBotonImprimir(true));
        tblPrenda.getColumnModel().getColumn(6).setCellRenderer(new MiRenderBotonVer(true));
    }

    public MovimientoM getMovimiento() {
        int selectedRow = tblPrenda.getSelectedRow();
        MovimientoM oModeloM = null;
        if (selectedRow != -1) {
            oModeloM = (MovimientoM) tblPrenda.getValueAt(selectedRow, 7);
            dispose();
        }
        return oModeloM;
    }

    private void cargarTabla() {
        MovimientoC oC = new MovimientoC();
        List<MovimientoM> oMs = oC.listarMovimientosTodoBloque(xIdTienda);
        @SuppressWarnings("LocalVariableHidesMemberVariable")
        ArrayList oList;
        limpiarTabla();
        if (oMs != null) {
            int size = oMs.size();
            for (int a = 0; a < size; a++) {
                oList = new ArrayList();
                oList.add(oMs.get(a).getFecha());
                oList.add(oMs.get(a).getHora());
                oList.add(" " + oMs.get(a).getNomEmite());
                oList.add(" " + oMs.get(a).getNomRecibe());
                oList.add(oMs.get(a).getTipoSalida());
                oList.add(oMs.get(a).getCantidad());
                oList.add("");
                oList.add("");
                oList.add(oMs.get(a));
                ((ArrayListTableModel) tblPrenda.getModel()).addRow(oList);
            }
        }


        if (tblPrenda.getRowCount() == 0) {
            txtmensaje.setText(" No se encontraron movimientos realizados hasta la fecha.");
            txtmensaje.setForeground(Color.red);
        } else {
            txtmensaje.setText(" Se encontraron " + tblPrenda.getRowCount() + " movimientos realizados hasta la fecha.");
            txtmensaje.setForeground(Color.BLUE);
        }
    }

    private void limpiarTabla() {
        ArrayListTableModel oModelTbl = (ArrayListTableModel) tblPrenda.getModel();
        int i = oModelTbl.getRowCount();
        for (int a = 0; a < i; a++) {
            oModelTbl.removeRow(0);
        }
    }
}
